package com.mingtu.jgspatrol.activity;

import static com.mingtu.common.utils.Constant.TUI_CALLING_MESSAGE;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.widget.RadioGroup;

import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.ha.adapter.AliHaAdapter;
import com.alibaba.ha.adapter.AliHaConfig;
import com.alibaba.ha.adapter.Plugin;
import com.alibaba.ha.adapter.service.tlog.TLogLevel;
import com.alibaba.ha.adapter.service.tlog.TLogService;
import com.baidu.mobstat.StatService;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.DeviceUtils;
import com.blankj.utilcode.util.EncodeUtils;
import com.blankj.utilcode.util.EncryptUtils;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.MetaDataUtils;
import com.blankj.utilcode.util.SPStaticUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.flyco.tablayout.listener.CustomTabEntity;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.gyf.immersionbar.ImmersionBar;
import com.hjq.gson.factory.GsonFactory;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.interfaces.OnConfirmListener;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.HttpHeaders;
import com.lzy.okgo.model.Response;
import com.mingtu.bio.adapter.FilteClassAdapter;
import com.mingtu.bio.fragment.BioFindFragment;
import com.mingtu.bio.fragment.BioFragment;
import com.mingtu.bio.view.FilterAnimalView;
import com.mingtu.center.activity.MyCollectActivity;
import com.mingtu.center.activity.MyOffLineMapActivity;
import com.mingtu.center.activity.MyTrackActivity;
import com.mingtu.common.Eventbus.MyEventBus;
import com.mingtu.common.activity.LoginActivity;
import com.mingtu.common.bean.UserInfoBean;
import com.mingtu.common.callback.ResultCallback;
import com.mingtu.common.entity.TabEntity;
import com.mingtu.common.utils.ActivityUtil;
import com.mingtu.common.utils.Constant;
import com.mingtu.common.utils.IntentUtils;
import com.mingtu.common.utils.MapPermissionsUtils;
import com.mingtu.common.utils.MyLogUtil;
import com.mingtu.common.utils.SPTools;
import com.mingtu.common.utils.StatusBarUtil;
import com.mingtu.common.view.MyDialog;
import com.mingtu.contacts.utils.AppIdAuthUtil;
import com.mingtu.contacts.utils.CheckSumBuilder;
import com.mingtu.contacts.utils.SelfNotificationConfigFetcher;
import com.mingtu.jgspatrol.BuildConfig;
import com.mingtu.jgspatrol.R;
import com.mingtu.jgspatrol.adapter.LayerAdapter;
import com.mingtu.jgspatrol.adapter.TabbarAdapter;
import com.mingtu.jgspatrol.base.MyBaseActivity;
import com.mingtu.jgspatrol.bean.YXRegisterBean;
import com.mingtu.jgspatrol.callback.MyStringDialogCallback;
import com.mingtu.jgspatrol.databinding.ActivityMainBinding;
import com.mingtu.jgspatrol.fragment.IndexFragment3;
import com.mingtu.jgspatrol.fragment.LotFragment;
import com.mingtu.jgspatrol.fragment.MineFragment;
import com.mingtu.jgspatrol.fragment.TrackFragment;
import com.mingtu.jgspatrol.utils.MyConstant;
import com.mingtu.jgspatrol.utils.MySPTools;
import com.mob.MobSDK;
import com.netease.lava.nertc.sdk.NERtcOption;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.Observer;
import com.netease.nimlib.sdk.RequestCallback;
import com.netease.nimlib.sdk.StatusCode;
import com.netease.nimlib.sdk.auth.AuthService;
import com.netease.nimlib.sdk.auth.AuthServiceObserver;
import com.netease.nimlib.sdk.auth.LoginInfo;
import com.netease.nimlib.sdk.lifecycle.SdkLifecycleObserver;
import com.netease.yunxin.nertc.ui.CallKitUI;
import com.netease.yunxin.nertc.ui.CallKitUIOptions;
import com.taobao.sophix.SophixManager;
import com.tencent.bugly.crashreport.CrashReport;
import com.tencent.smtt.sdk.QbSdk;
import com.tencent.smtt.sdk.TbsListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import cn.jiguang.api.utils.JCollectionAuth;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.ups.JPushUPSManager;

@Route(path = "/app/MainActivity")
public class MainActivity extends MyBaseActivity<ActivityMainBinding> {
    private ArrayList<Fragment> mFragments = new ArrayList<>();
    private ArrayList<CustomTabEntity> mTabEntities = new ArrayList<>();
    private TrackFragment tabTrack;
    private static final String[] mTitles = {"首页", "生物发现", "", "智慧物联", "我的"};
    private static final int[] mSeleIcons = {R.mipmap.tab1_selected, R.mipmap.tab3_selected, 0, R.mipmap.tab2_selected, R.mipmap.tab4_selected};
    private static final int[] mNormalIcons = {R.mipmap.tab1_normal, R.mipmap.tab3_normal, 0, R.mipmap.tab2_normal, R.mipmap.tab4_normal};
    private long firstPressedTime;
    private BioFindFragment bioFindFragment;
    private boolean mIsKickedOffline = false;
    private boolean mIsUserSigExpired = false;
    private String userName;
    private BioFragment bioFragment;
    private Handler msgHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 200:
                    indexFragment3.getNoticeList();
                    break;
            }
        }
    };
    private IndexFragment3 indexFragment3;
    private String mobile;
    private String[] classText = {"动物", "鸟类"};

    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected void initData() {
        //首页
//        indexFragment2 = IndexFragment2.getInstance();
        indexFragment3 = IndexFragment3.getInstance();
        mFragments.add(indexFragment3);

        //生物发现
        bioFindFragment = new BioFindFragment();
        bioFindFragment.setOnClickFilteListener(new BioFindFragment.OnClickFilteListener() {
            @Override
            public void onClickFilte() {
                bioFragment = bioFindFragment.getBioFragment(); //因为懒加载的原因，bioFragment 需要在此处获取
                boolean isOpen = binding.layoutDrawerAnimal.isDrawerOpen(binding.layoutRightDrawer);
                if (isOpen) {
                    closeRightDrawers();
                } else {
                    openRightDrawer();
                    KeyboardUtils.hideSoftInput(MainActivity.this);
                }
            }
        });
        mFragments.add(bioFindFragment);

        //巡护
        tabTrack = new TrackFragment();
        mFragments.add(tabTrack);

        //智慧物联
        mFragments.add(new LotFragment());

        //我的
        mFragments.add(new MineFragment());

        binding.viewPager.setOffscreenPageLimit(5);//需要设置此值
        binding.viewPager.setAdapter(new TabbarAdapter(getSupportFragmentManager(), mFragments));

        for (int i = 0; i < mTitles.length; i++) {
            mTabEntities.add(new TabEntity(mTitles[i], mSeleIcons[i], mNormalIcons[i]));
        }

        binding.commonTabLayout.setTabData(mTabEntities);
        binding.commonTabLayout.setOnTabSelectListener(onTabSelectListener);
        binding.viewPager.addOnPageChangeListener(onPageChangeListener);
        binding.viewPager.setCurrentItem(0);
        binding.tvTitle.setText(mTitles[0]);


        String geoFenceFlag = SPStaticUtils.getString(SPTools.GeoFenceFlag); //是否是出地理围栏导致的巡护结束 1:巡护时间超过8小时  自动结束  2:超出地理围栏 巡护结束
        if (!StringUtils.isEmpty(geoFenceFlag)) {
            String str = "";
            if (geoFenceFlag.equals(Constant.AUTO_END_TRACK_TYPE_ONE)) {
                str = "巡护时间超出" + MyConstant.TRACK_AUTO_END_TIME / 3600 + "小时，已经自动结束巡护！";
            } else if (geoFenceFlag.equals(Constant.AUTO_END_TRACK_TYPE_TWO)) {
                str = "巡护超出地理围栏，已经自动结束巡护！";
            }
            MyDialog dialog = new MyDialog(MainActivity.this);
            dialog.setMessage(str);
            dialog.setOnSureClickListener(new MyDialog.OnSureClickListener() {
                @Override
                public void onSureClick() {
                    SPStaticUtils.remove(SPTools.GeoFenceFlag);
                    dialog.dismiss();
                }
            });
            dialog.show();
        }


        EventBus.getDefault().register(this);

        //百度统计，上传用户识别ID
        //StatService.setUserId(context, alias + "_" + phone);
//        XGPushConfig.enableDebug(this,true);
//        XGPushManager.registerPush(this, new XGIOperateCallback() {
//            @Override
//            public void onSuccess(Object data, int flag) {
//                //token在设备卸载重装的时候有可能会变
//                Log.d("TPush", "注册成功，设备token为：" + data);
//            }
//
//            @Override
//            public void onFail(Object data, int errCode, String msg) {
//                Log.d("TPush", "注册失败，错误码：" + errCode + ",错误信息：" + msg);
//            }
//        });

//        initIMListener();
//        initChannel();

        List<String> tags = new ArrayList<>();
        mobile = SPStaticUtils.getString(SPTools.mobile);//联系方式
        userName = SPStaticUtils.getString(SPTools.userName);//联系方式
        if (!StringUtils.isEmpty(mobile)) {
            tags.add(mobile);
        }

        SophixManager.getInstance().setTags(tags); //设置灰度发布的标签，需要在queryAndLoadNewPatch之前调用
        //加载补丁包
        SophixManager.getInstance().queryAndLoadNewPatch();
        //TLog远程日志
        initHa(mobile, userName);
        initPolicyGrant();
        //腾讯浏览服务
        initQb();

        if (JPushInterface.isPushStopped(context)) {
            JPushUPSManager.turnOnPush(context, null);
        }

        getUserInfo();

        NIMClient.getService(SdkLifecycleObserver.class).observeMainProcessInitCompleteResult(new Observer<Boolean>() {
            @Override
            public void onEvent(Boolean b) {
                if (b != null && b) {
                    registeriM(new ResultCallback() {
                        @Override
                        public void result(Object token) {
                            NIMClientLogin(mobile, String.valueOf(token));
                        }
                    });
                }
            }
        }, true);
        NIMClientObserveOnlineStatus();

        addClickListener(this, binding.layoutTrack, binding.layoutCollect, binding.tvOffLine, binding.ivTrack);

    }

    //隐私声明
    private void initPolicyGrant() {
        MobSDK.submitPolicyGrantResult(true);

        //关闭SDK自启动,为了上架审核，不影响推送
//        JCollectionAuth.enableAutoWakeup(context, false);
        JPushInterface.setDebugMode(AppUtils.isAppDebug());
        JCollectionAuth.setAuth(this, true);
        JPushInterface.init(this);

        String appChannel = "mingtu";
        String userName = SPStaticUtils.getString(SPTools.userName);
        if (!StringUtils.isEmpty(userName)) {
            appChannel = userName;
        }
        String baiduStatAppkey = MetaDataUtils.getMetaDataInApp("BaiduMobAd_STAT_ID");
        String buglyAppkey = MetaDataUtils.getMetaDataInApp("com.tencent.bugly.apikey");
        // SDK初始化，该函数不会采集用户个人信息，也不会向百度移动统计后台上报数据
        StatService.init(context, baiduStatAppkey, appChannel);
        // 通过该接口可以控制敏感数据采集，true表示可以采集，false表示不可以采集，
        // 该方法一定要最优先调用，请在StatService.start(this)之前调用，采集这些数据可以帮助App运营人员更好的监控App的使用情况，
        // 建议有用户隐私策略弹窗的App，用户未同意前设置false,同意之后设置true
        StatService.setAuthorizedState(this, true);
        // 自动埋点，建议在Application中调用。否则可能造成部分页面遗漏，无法完整统计。
//        StatService.autoTrace(this, true, true);

        // setSendLogStrategy已经@deprecated，建议使用新的start接口
        // 如果没有页面和自定义事件统计埋点，此代码一定要设置，否则无法完成统计
        // 进程第一次执行此代码，会导致发送上次缓存的统计数据；若无上次缓存数据，则发送空启动日志
        // 由于多进程等可能造成Application多次执行，建议此代码不要埋点在Application中，否则可能造成启动次数偏高
        // 建议此代码埋点在统计路径触发的第一个页面中，若可能存在多个则建议都埋点
        StatService.start(this);

        //bugly
        CrashReport.initCrashReport(getApplicationContext(), buglyAppkey, false);
        CrashReport.setDeviceId(context, DeviceUtils.getUniqueDeviceId()); // 设备id
        CrashReport.setDeviceModel(context, DeviceUtils.getModel()); //设备型号
        CrashReport.setAppVersion(context, AppUtils.getAppVersionName());
        CrashReport.setAppPackage(context, AppUtils.getAppPackageName());
        CrashReport.setAppChannel(context, mobile + "_" + userName);
    }


    private void initQb() {
        /* 设置允许移动网络下进行内核下载。默认不下载，会导致部分一直用移动网络的用户无法使用x5内核 */
        QbSdk.setDownloadWithoutWifi(true);

        /* SDK内核初始化周期回调，包括 下载、安装、加载 */
        QbSdk.setTbsListener(new TbsListener() {

            /**
             * @param stateCode 110: 表示当前服务器认为该环境下不需要下载
             */
            @Override
            public void onDownloadFinish(int stateCode) {
                MyLogUtil.i("QbSdk", "onDownloadFinished: " + stateCode);
            }

            /**
             * @param stateCode 200、232安装成功
             */
            @Override
            public void onInstallFinish(int stateCode) {
                MyLogUtil.i("QbSdk", "onInstallFinished: " + stateCode);
            }

            /**
             * 首次安装应用，会触发内核下载，此时会有内核下载的进度回调。
             * @param progress 0 - 100
             */
            @Override
            public void onDownloadProgress(int progress) {
                MyLogUtil.i("QbSdk", "Core Downloading: " + progress);
            }
        });

        /* 此过程包括X5内核的下载、预初始化，接入方不需要接管处理x5的初始化流程，希望无感接入 */
        QbSdk.initX5Environment(this, new QbSdk.PreInitCallback() {
            @Override
            public void onCoreInitFinished() {
                // 内核初始化完成，可能为系统内核，也可能为系统内核
            }

            /**
             * 预初始化结束
             * 由于X5内核体积较大，需要依赖wifi网络下发，所以当内核不存在的时候，默认会回调false，此时将会使用系统内核代替
             * 内核下发请求发起有24小时间隔，卸载重装、调整系统时间24小时后都可重置
             * @param isX5 是否使用X5内核
             */
            @Override
            public void onViewInitFinished(boolean isX5) {
//                MyLogUtil.i(TAG, "onViewInitFinished: " + isX5);
            }
        });
    }

    @Override
    protected void initView() {
        hideHeadView();
        StatusBarUtil.addStatusBarHeight(binding.statusBarView);
        StatusBarUtil.addStatusBarHeight(binding.statusBarViewLeftDrawer);
        //沉侵式状态栏
        ImmersionBar immersionBar = ImmersionBar.with(this);
        immersionBar.statusBarDarkFont(true);  //状态栏字体是深色，不写默认为亮色
        immersionBar.init();

        binding.layoutTitle.setVisibility(View.GONE);
        binding.statusBarView.setVisibility(View.GONE);


        //图层
        LayerAdapter adapter = new LayerAdapter(context, binding.mgv);
        binding.mgv.setAdapter(adapter);
        adapter.setOnItemClickListener(new LayerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position, boolean isChecked) {
                closeDrawers();
                tabTrack.menuEnevt(position, !isChecked);
            }
        });

        binding.layoutDrawerAnimal.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED); //初始状态禁止右侧视图滑出
        binding.filterAnimalView.setOnClickListener(new FilterAnimalView.OnClickListener() {
            @Override
            public void onClickCancel() {
                closeRightDrawers();
            }

            @Override
            public void onClickReset(String kmName, String classType, String levelName, String genusName) {
                if (bioFragment != null)
                    bioFragment.reset(kmName, genusName, levelName, classType); //重置数据
                closeRightDrawers();
            }

            @Override
            public void onClickSure(String kmName, String classType, String levelName, String genusName) {
                closeRightDrawers();
                if (bioFragment != null)
                    bioFragment.refresh(kmName, genusName, levelName, classType); //筛选之后 重置数据
            }
        });


        List<String> classList = new ArrayList<>();
        for (int i = 0; i < classText.length; i++) {
            classList.add(classText[i]);
        }
        FilteClassAdapter filteClassAdapter = binding.filterAnimalView.getFilteClassAdapter();
        filteClassAdapter.upData(classList);


    }

    @Override
    protected void getData() {
        binding.radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                switch (i) {
                    case R.id.rb_map1: //普通地图
                        tabTrack.setMapType(0);
                        break;
                    case R.id.rb_map2://卫星地图
                        tabTrack.setMapType(1);
                        break;
                    case R.id.rb_map3://谷歌地图
                        tabTrack.setMapType(2);
                        break;


                }
            }
        });
    }


    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.layout_track:
                IntentUtils.getInstance().readyGo(MainActivity.this, MyTrackActivity.class);
                break;
            case R.id.layout_collect:
                IntentUtils.getInstance().readyGo(MainActivity.this, MyCollectActivity.class);
                break;
            case R.id.tv_off_line:
                IntentUtils.getInstance().readyGo(MainActivity.this, MyOffLineMapActivity.class);
                break;
            case R.id.iv_track:
                binding.layoutTitle.setVisibility(View.VISIBLE);
                binding.statusBarView.setVisibility(View.VISIBLE);
                binding.viewPager.setCurrentItem(2, false);
                binding.tvTitle.setText("资源地图");
                if (!XXPermissions.isGranted(this, Permission.ACCESS_COARSE_LOCATION) ||
                        !XXPermissions.isGranted(this, Permission.ACCESS_FINE_LOCATION)) {

                    tabTrack.setLocationPermissions();

                }
                break;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // 点击手机上的返回键，返回上一层
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (System.currentTimeMillis() - firstPressedTime < 2000) {
                ActivityUtil.removeAllActivity();
            } else {
                ToastUtils.showLong("再按一次退出");
                firstPressedTime = System.currentTimeMillis();
            }
        }
        return false;
    }

    @Override
    protected void onStop() {
        super.onStop();

    }

    @Override
    protected void onRestart() {
        super.onRestart();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onNetChange(boolean netWorkState) {
        super.onNetChange(netWorkState);
        try {
            tabTrack.setNetWorkState(netWorkState);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == XXPermissions.REQUEST_CODE) {
            if (XXPermissions.isGranted(this, Permission.ACCESS_COARSE_LOCATION) ||
                    XXPermissions.isGranted(this, Permission.ACCESS_FINE_LOCATION)) {
                //获取到GPS 权限
                MapPermissionsUtils.with(context).initGpsStatus();
            } else {
                ToastUtils.showLong("GPS权限获取失败！");
            }
            if (!XXPermissions.isGranted(this, Permission.NOTIFICATION_SERVICE)) {
                //通知权限
                ToastUtils.showLong("通知权限获取失败！");
            }

            if (!XXPermissions.isGranted(this, Permission.MANAGE_EXTERNAL_STORAGE)) {
                //存储权限
                ToastUtils.showLong("存储权限获取失败！");
            }

            if (!XXPermissions.isGranted(this, Permission.RECORD_AUDIO)) {
                //录音权限
                ToastUtils.showLong("录音权限获取失败！");
            }
        }
    }

    @Subscribe
    public void onStringEvent(MyEventBus event) {
        //业务逻辑
        String message = event.getMessgae();
        if (message.equals(MyConstant.SHOW_FILTE_BIO)) {
            binding.layoutDrawerAnimal.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
        } else if (message.equals(MyConstant.CLOSE_FILTE_BIO)) {
            binding.layoutDrawerAnimal.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
            KeyboardUtils.hideSoftInput(MainActivity.this);
        } else if (message.equals(MyConstant.REFRESH_MSG)) {
            if (indexFragment3 != null) { //刷新消息通知
                Message msg = Message.obtain();
                msg.what = 200;
                msgHandler.sendMessage(msg);
            }
        } else if (message.equals(TUI_CALLING_MESSAGE)) {
            //系统决定暂时无法解决
//            AppUtils.launchApp(AppUtils.getAppPackageName());
        }
    }

    /**
     * 隐藏底部tab
     */
    public void hideBottomTab() {
        binding.layoutTab.setVisibility(View.GONE);
        binding.ivTrack.setVisibility(View.GONE);
    }


    /**
     * 显示底部tab
     */
    public void showBottomTab() {
        binding.layoutTab.setVisibility(View.VISIBLE);
        binding.ivTrack.setVisibility(View.VISIBLE);
    }


    /**
     * 关闭左侧边栏
     */
    public void closeDrawers() {
        binding.drawerLayout.closeDrawer(binding.layoutLeftDrawers);
    }

    /**
     * 打开左侧边栏
     */
    public void openDrawer() {
        binding.drawerLayout.openDrawer(binding.layoutLeftDrawers);
    }

    /**
     * 关闭右侧边栏
     */
    public void closeRightDrawers() {
        binding.layoutDrawerAnimal.closeDrawer(binding.layoutRightDrawer);
    }

    /**
     * 打开右侧边栏
     */
    public void openRightDrawer() {
        binding.layoutDrawerAnimal.openDrawer(binding.layoutRightDrawer);
    }


    private OnTabSelectListener onTabSelectListener = new OnTabSelectListener() {
        @Override
        public void onTabSelect(int position) {
            binding.viewPager.setCurrentItem(position, false);
            binding.tvTitle.setText(mTitles[position]);
            if (position == 2) {
                binding.drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
                binding.layoutDrawerAnimal.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
            } else if (position == 1) {
                binding.drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
                binding.layoutDrawerAnimal.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
            } else {
                binding.drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
                binding.layoutDrawerAnimal.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
            }

            binding.layoutTitle.setVisibility(View.GONE);
            binding.statusBarView.setVisibility(View.GONE);
//            ivFilte.setVisibility(View.GONE);

            if (position == 1 || position == 2) {
                binding.layoutTitle.setVisibility(View.VISIBLE);
                binding.statusBarView.setVisibility(View.VISIBLE);
            } else {
                binding.layoutTitle.setVisibility(View.GONE);
                binding.statusBarView.setVisibility(View.GONE);
            }

            if (position == 2) {
//                ivFilte.setVisibility(View.VISIBLE);
                openDrawer();
            } else {
                closeDrawers();
            }

            //语音机器人显示逻辑
            if (position == 0) {
                ImmersionBar immersionBar = ImmersionBar.with(MainActivity.this);
                immersionBar.statusBarDarkFont(true);  //状态栏字体是深色，不写默认为亮色
                immersionBar.init();
            } else {
                ImmersionBar immersionBar = ImmersionBar.with(MainActivity.this);
                immersionBar.statusBarDarkFont(false);  //状态栏字体是深色，不写默认为亮色
                immersionBar.init();
            }

        }

        @Override
        public void onTabReselect(int position) {

        }
    };

    private ViewPager.OnPageChangeListener onPageChangeListener = new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        }

        @Override
        public void onPageSelected(int position) {
            //语音机器人显示逻辑
            binding.commonTabLayout.setCurrentTab(position);
            binding.tvTitle.setText(mTitles[position]);

        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    };


    //用于兼容登录过的用户
    private void getUserInfo() {
        OkGo.<String>get(Constant.getInstance().GET_USER_INFO)
                .tag(this)
                .execute(new MyStringDialogCallback(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {
                            try {
                                Gson gson = GsonFactory.getSingletonGson();
                                UserInfoBean userInfoBean = new UserInfoBean();
                                userInfoBean = gson.fromJson(result, UserInfoBean.class);

                                UserInfoBean.UserBean userBean = userInfoBean.getUser();
                                String username = userBean.getUsername();
                                String mobile = userBean.getMobile();
                                String name = userBean.getName();

                                String userId = userBean.getUserId();
                                SPStaticUtils.put(SPTools.userId, userId);

                                List<String> isLeaderList = new ArrayList<>();
                                List<UserInfoBean.UserBean.RoleListBean> roleList = userBean.getRoleList();

                                if (roleList != null && roleList.size() > 0) {
                                    for (int i = 0; i < roleList.size(); i++) {
                                        String isLeader = roleList.get(i).getIsLeader(); //isLeader 1：职员 0：普通
                                        isLeaderList.add(isLeader);
                                    }

                                }

                                if (roleList != null && roleList.size() > 0) {
                                    UserInfoBean.UserBean.RoleListBean roleListBean = roleList.get(0);
                                    List<UserInfoBean.UserBean.RoleListBean.MenuAppListBean> menuAppListBean = roleListBean.getMenuAppList();
                                    if (menuAppListBean != null && menuAppListBean.size() > 0) {
                                        List<String> typeList = new ArrayList<>();
                                        for (int i = 0; i < menuAppListBean.size(); i++) {
                                            String path = menuAppListBean.get(i).getPath(); //isLeader 1：职员 0：普通
                                            typeList.add(path);
                                        }
                                        //是否有下载图片、视频的权限
                                        if (typeList.contains("download")) {
                                            SPStaticUtils.put(SPTools.download, true);
                                        } else {
                                            SPStaticUtils.put(SPTools.download, false);
                                        }

                                        //控制户外屏的权限
                                        if (typeList.contains("outdoorControl")) {
                                            SPStaticUtils.put(SPTools.outdoorControl, true);
                                        } else {
                                            SPStaticUtils.put(SPTools.outdoorControl, false);
                                        }
                                    }
                                }

                                if (!StringUtils.isEmpty(mobile)) {
                                    SPStaticUtils.put(SPTools.mobile, mobile);//保存手机号
                                } else {
                                    SPStaticUtils.put(SPTools.mobile, "");
                                }
                                if (!StringUtils.isEmpty(name)) {
                                    SPStaticUtils.put(SPTools.userName, name);//保存用户名
                                } else {
                                    SPStaticUtils.put(SPTools.userName, "");
                                }

                                //是否是领导权限
                                if (isLeaderList.contains("1")) {
                                    SPStaticUtils.put(SPTools.isLeader, true);
                                } else {
                                    SPStaticUtils.put(SPTools.isLeader, false);
                                }

                                JPushInterface.setAlias(context, Constant.TYPE_BIND_ALIAS, username);
//                                liteavInit();
                            } catch (JsonSyntaxException e) {
                                e.printStackTrace();
                            }

                        }

                    }

                    @Override
                    public void onError(Response<String> response) {
                        String result = response.body();
                        MyLogUtil.e(getClass().getSimpleName(), "onError==" + result);
                    }
                });


    }

    public void checkUserStatus() {
        String tip = "";
        String trackFlag = SPStaticUtils.getString(SPTools.trackFlag);
        if (trackFlag.equals("true")) { //巡护过程中被踢的时候先结束巡护
            tabTrack.strackEndEvent();
        }
        if (mIsKickedOffline) {
            tip = getString(R.string.app_user_kicked_offline);

        } else if (mIsUserSigExpired) {
            tip = getString(R.string.app_user_sig_expired);
        }
        if (mIsKickedOffline || mIsUserSigExpired) {
            JPushInterface.deleteAlias(context, Constant.TYPE_BIND_ALIAS);
            JPushUPSManager.turnOffPush(context, null);
        }
        new XPopup.Builder(MainActivity.this)
                .isDestroyOnDismiss(true)
                .dismissOnTouchOutside(false)
                .hasShadowBg(true)
                .asConfirm(context.getResources().getString(R.string.text_tip),
                        tip,
                        context.getResources().getString(R.string.text_cancle), context.getResources().getString(R.string.text_sure),
                        new OnConfirmListener() {
                            @Override
                            public void onConfirm() {
                                NIMClient.getService(AuthService.class).logout();
                                IntentUtils.getInstance().readyGo(ActivityUtil.getTopActivity(), LoginActivity.class);
                                ActivityUtil.removeAllActivity();

                            }
                        }, null,
                        true)
                .show();


        SPStaticUtils.put(MySPTools.mIsKickedOffline, mIsKickedOffline);
        SPStaticUtils.put(MySPTools.mIsUserSigExpired, mIsUserSigExpired);

    }

    private void initHa(String mobile, String userName) {
        String userNick = "thspatrol";
        if (!StringUtils.isEmpty(userName)) {
            userNick = userName;
        } else if (!StringUtils.isEmpty(mobile)) {
            userNick = mobile;
        }
        AliHaConfig config = new AliHaConfig();
        config.appKey = BuildConfig.EMAS_APP_KRY; //配置项：appkey
        config.appVersion = BuildConfig.VERSION_NAME;
        config.appSecret = BuildConfig.EMAS_APP_SECRET; //配置项：appsecret
        config.channel = "channel"; //配置项：应用的渠道号标记，自定义
        config.userNick = userNick; //配置项：用户的昵称
        config.application = getApplication(); //配置项：应用指针
        config.context = getApplicationContext(); //配置项：应用上下文
        config.isAliyunos = false; //配置项：是否为yunos
        config.rsaPublicKey = BuildConfig.TLOG_RSA_PUBLIC_LEY; //配置项：tlog公钥
        AliHaAdapter.getInstance().addPlugin(Plugin.tlog);
        AliHaAdapter.getInstance().addPlugin(Plugin.apm);
        AliHaAdapter.getInstance().openDebug(AppUtils.isAppDebug());
        AliHaAdapter.getInstance().start(config);
        TLogService.updateLogLevel(TLogLevel.DEBUG); //配置项：控制台可拉取的日志级别

    }

    private void registeriM(ResultCallback callback) {
        String nonce = AppIdAuthUtil.newNonce();
        long curTime = TimeUtils.getNowMills();
        String appKey = BuildConfig.YX_APP_KEY;
        String appSecret = BuildConfig.YX_APP_SECRET;
        long ttl = 600;

        String data = appKey + mobile + curTime + ttl + appSecret;
        String signature = EncryptUtils.encryptSHA1ToString(data).toLowerCase();
        HashMap<String, Object> authMap = new HashMap<>();
        authMap.put("signature", signature);
        authMap.put("curTime", curTime);
        authMap.put("ttl", ttl);
        String jsonStr = GsonUtils.toJson(authMap);

        String myToken = EncodeUtils.base64Encode2String(jsonStr.getBytes());

        HttpHeaders headers = new HttpHeaders();
        headers.put("AppKey", appKey);
        headers.put("Nonce", nonce);
        headers.put("CurTime", String.valueOf(curTime / 1000));
        headers.put("CheckSum", CheckSumBuilder.getCheckSum(appSecret, nonce, String.valueOf(curTime / 1000)));


        HashMap<String, Object> hashMap = new HashMap<>();

        HashMap<String, Object> userInfo = new HashMap<>();
        userInfo.put("name", userName);
        userInfo.put("avatar", MyConstant.HEAD_URL);
        userInfo.put("mobile", mobile);

        hashMap.put("account_id", mobile);
        hashMap.put("user_information", userInfo);
        String str = GsonUtils.toJson(hashMap);
        OkGo.<String>post(MyConstant.POST_YX_REGISTER)
                .tag(this)
                .headers(headers)
                .upJson(str)
                .execute(new MyStringDialogCallback(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {
                            try {
                                Gson gson = GsonFactory.getSingletonGson();
                                YXRegisterBean registerBean = new YXRegisterBean();
                                registerBean = gson.fromJson(result, YXRegisterBean.class);
                                int code = registerBean.getCode();
                                MyLogUtil.e("NIMRegister", "code==" + code);
                                if (code == 200) { //注册成功
                                    callback.result(myToken);
                                } else if (code == 102405) { //用户存在
                                    callback.result(myToken);
                                } else if (code == 102434) {
                                    ToastUtils.showLong("音视频注册，超过最大账号数！");
                                } else if (code == 102449) {
                                    ToastUtils.showLong("音视频注册，账号请求需要重试！");
                                } else if (code == 103451) {
                                    ToastUtils.showLong("音视频注册，用户资料反垃圾！");
                                } else if (code == 500) {
                                    ToastUtils.showLong("音视频注册，服务器内部错误!");
                                } else if (code == 414) {
                                    ToastUtils.showLong("音视频注册，参数错误!");
                                } else if (code == 403) {
                                    ToastUtils.showLong("音视频注册，鉴权失败!");
                                }
                            } catch (JsonSyntaxException e) {
                                throw new RuntimeException(e);
                            }
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        String result = response.body();
                        MyLogUtil.e(getClass().getSimpleName(), "onError==" + result);
                    }
                });
    }

    private void NIMClientLogin(String accid, String token) {
        //动态token登录
        LoginInfo.LoginInfoBuilder loginInfoBuilder = new LoginInfo.LoginInfoBuilder(accid, token, 1, "");
        LoginInfo loginInfo = loginInfoBuilder.build();
        RequestCallback<LoginInfo> callback =
                new RequestCallback<LoginInfo>() {
                    @Override
                    public void onSuccess(LoginInfo param) {
                        MyLogUtil.e("NIMClientLogin", "NIMClientLogin  success");
                    }

                    @Override
                    public void onFailed(int code) {
                        MyLogUtil.e("NIMClientLogin", "NIMClientLogin  faile");
                    }

                    @Override
                    public void onException(Throwable exception) {
                        MyLogUtil.e("NIMClientLogin", "NIMClientLogin  exception=" + exception.getMessage());
                    }
                };

        //执行手动登录
        NIMClient.getService(AuthService.class).login(loginInfo).setCallback(callback);
    }

    private void NIMClientObserveOnlineStatus() {
        NIMClient.getService(AuthServiceObserver.class).observeOnlineStatus(
                new Observer<StatusCode>() {
                    public void onEvent(StatusCode status) {
                        //获取状态的描述
                        String desc = status.getDesc();
                        MyLogUtil.e("NIMOnlineStatus", "NStatusCode=" + status + ",desc==" + desc);
                        if (status == StatusCode.KICKOUT) {
                            // 被踢出、账号被禁用、密码错误等情况，自动登录失败，需要返回到登录界面进行重新登录操作
                            mIsKickedOffline = true;
                            checkUserStatus();
                        }

                        if (status == StatusCode.LOGINED) {
                            CallKitUIOptions options = new CallKitUIOptions.Builder()
                                    // 必要：音视频通话 sdk appKey，用于通话中使用
                                    .rtcAppKey(BuildConfig.YX_APP_KEY)
                                    // 通话接听成功的超时时间单位 毫秒，默认 30s
                                    .timeOutMillisecond(30 * 1000L)
                                    // 此处为 收到来电时展示的 notification 相关配置，如图标，提示语等。
                                    .notificationConfigFetcher(new SelfNotificationConfigFetcher())
                                    // 收到被叫时若 app 在后台，在恢复到前台时是否自动唤起被叫页面，默认为 true
                                    .resumeBGInvitation(true)
                                    // 请求 rtc token 服务，若非安全模式则不需设置（V1.8.0 版本之前需要配置，V1.8.0 及之后版本无需配置）
                                    //.rtcTokenService((uid, callback) -> requestRtcToken(appKey, uid, callback)) // 自己实现的 token 请求方法
                                    // 设置初始化 RTC SDK 相关配置，按照所需进行配置
                                    .rtcSdkOption(new NERtcOption())
                                    // 呼叫组件初始化 rtc 范围，NECallInitRtcMode.GLOBAL-全局初始化，
                                    // NECallInitRtcMode.IN_NEED-每次通话进行初始化以及销毁，全局初始化有助于更快进入首帧页面，
                                    // 当结合其他组件使用时存在 rtc 初始化冲突可设置 NECallInitRtcMode.IN_NEED
                                    // 或当结合其他组件使用时存在 rtc 初始化冲突可设置 NECallInitRtcMode.IN_NEED_DELAY_TO_ACCEPT
                                    .build();
// 不要重复初始化组件可能会产生 sdk 初始化失败问题
                            CallKitUI.init(getApplicationContext(), options);
                        }

                    }
                }, true);
    }

}

